'use strict'

const _ = require('underscore')
const Promise = require('bluebird')
const AV = require('leanengine')
const utils = require('../libs/utils')

const func = {
  create (req) {
    var name = req.params.name
    var location = req.params.location
    var startAt = new Date(req.params.startAt)
    var description = req.params.description
    var subTournaments = req.params.subTournaments
    var chairUmpirePhone = req.params.chairUmpirePhone
    var tournament = new AV.Object('Tournament')
    var s = {}
    var subTournamentsObj = subTournaments.map(el => {
      var subTournament = new AV.Object('SubTournament')
      _.each(el, (val, key) => {
        subTournament.set(key, val)
      })
      // subTournament.set('tournament', new AV.Object.createWithoutData('Tournament', ,))
      return subTournament
    })
    return AV.Object.saveAll(subTournamentsObj)
    .then(ret => {
      console.log(ret)
      s.subTournamentsObjs = ret
      var relation = tournament.relation('subTournaments')
      ret.forEach(el => {
        relation.add(el)
      })
      return new AV.Query('_User').equalTo('mobilePhoneNumber', chairUmpirePhone).find()
    }).then(ret => {
      return tournament.save({
        chairUmpire: {
          className: '_User',
          objectId: ret[0].id,
          __type: 'Pointer'
        },
        name,
        location,
        startAt,
        description
      })
    }).then(ret => {
      var promises = s.subTournamentsObjs.map(el => {
        el.save({
          tournament: ret
        })
      })
      return Promise.all(promises)
    })
  },
  get (req, chairUmpire) {
    var _s = {}
    var ids = req.params.ids
    var query
    query = new AV.Query('Tournament')
    if (ids) {
      query.equalTo('objectId', ids[0])
    }
    if (chairUmpire) {
      query.equalTo('chairUmpire', req.user)
    }
    return query.find()
    .then(ret => {
      _s.tournaments = ret
      var promises = ret.map(el => {
        return el.relation('subTournaments').query().find()
      })
      return Promise.all(promises)
    })
    .then(ret => {
      _s._tournaments = []
      ret.forEach((el, index) => {
        _s._tournaments[index] = _s.tournaments[index].toJSON()
        _s._tournaments[index].subTournaments = []
        el.forEach((el2, index2) => {
          _s._tournaments[index].subTournaments[index2] = el2.toJSON()
        })
      })
      console.log(_s._tournaments)
      return Promise.resolve(_s._tournaments)
    })
  },
  signUp (req) {
    const isSingle = req.params.isSingle
    const id = req.params.id
    const signUpObjId = isSingle ? req.user.id : req.params.doublesObjId
    return new AV.Query('SubTournament').get(id)
    .then(sub => {
      var signUpMembers =  sub.get('signUpMembers') || []
      if (isSingle) {
        if (signUpMembers.indexOf(signUpObjId) !== -1) {
          return Promise.reject({errMsg: 'has signed Up'})
        }
        signUpMembers.push(signUpObjId)
        return sub.save({signUpMembers})
      }
      return new AV.Query('Doubles')
      .get(signUpObjId).then(ret => {
        var relation = ret.relation('players')
        return relation.query().notEqualTo('objectId', req.user.id).find()
      }).then(ret => {
        console.log(ret)
        return new AV.Query('Doubles').equalTo('players', AV.Object.createWithoutData('_User', ret[0].id)).find()
      }).then(ret => {
        for (let i = 0, len = ret.length; i < len; i++) {
          if (signUpMembers.indexOf(ret[i].id) !== -1) {
            return Promise.reject({errMsg: 'your partner has signed up', errMsgCN: '你的搭档已经报名了'})
          }
        }
        signUpMembers.push(signUpObjId)
        return sub.save({signUpMembers})
      })
    })
  },
  signUpUmpire (req) {
    var id = req.params.id
    return new AV.Query('SubTournament').get(id)
    .then(ret => {
      var signUpUmpires =  ret.get('signUpUmpires') || []
      if (signUpUmpires.indexOf(req.user.id) !== -1) {
        return Promise.reject({errMsg: 'has signed Up umpire'})
      }
      signUpUmpires.push(req.user.id)
      return ret.save({signUpUmpires})
    })
  },

  getMyChairUmpiredTournaments (req) {
    return this.get(req, true)
  },

  getMyUmpireSubTournaments (req) {
    var query = new AV.Query('SubTournament')
    query.equalTo('umpires', req.user)
    query.include('tournament')
    return query.find().then(ret => {
      var arr = ret.map(el => {
        var tournament = el.get('tournament').toJSON()
        var r = el.toJSON()
        r.tournament = tournament
        return r
      })
      return Promise.resolve(arr)
    })
  },

  changeSubTournamentState (req) {
    const state = req.params.state
    const subTournamentObjId = req.params.subTournamentObjId
    return new AV.Query('SubTournament')
    .get(subTournamentObjId)
    .then(ret => {
      return ret.save({
        state
      })
    })
  }
}

AV.Cloud.define('tournament', function (req, res) {
  var promise
  if (!req.user) {
    promise = Promise.reject({
      msg: 'not loged in'
    })
  } else {
    promise = func[req.params.method](req)
  }
  return promise.then(function (ret) {
    res.success(ret)
  }).catch(function (err) {
    console.log(err)
    res.error(err)
  })
})
